<?php
declare(strict_types=1);


namespace app\admin\controller\system;

use app\admin\model\Attachment as AttachmentModel;
use app\common\Attribute\ClassTitle;
use app\common\Attribute\RequestMethod;
use app\common\Attribute\RequestTitle;
use app\common\controller\AmisAdminController;
use LhpAmis\Renderers\Amis;
use think\facade\Db;
use think\facade\Env;
use think\facade\Event;
use think\File;
use think\Image;

/**
 * 附件控制器
 */
#[ClassTitle(name: '附件')]
class Attachment extends AmisAdminController
{
    /**
     * 附件列表
     * @author dragonlhp <1458485514@qq.com>
     */
    #[RequestMethod(['GET,POST'])]
    #[RequestTitle('列表')]
    public function index()
    {
        if (request()->isPost()) {
            // 查询
            [$where, $page, $order] = $this->RequestData();
            // 数据列表
            $data_list = AttachmentModel::where($where)->order($order)->paginate($page);
            return $this->data($data_list);
        }

        return Amis::make()->TableBuilder()
            ->setSearch(['name' => '名称']) // 设置搜索框
            ->setSearchItems([
                ['mime_type', '类型'],
                ['original_name', '名称'],
                ['size', '大小'],
                ['upload_time', '上传时间', 'datetime'],
                ['status', '状态', 'switch'],
            ])
            ->addColumns([ // 批量添加数据列
                ['id', 'ID'],
                ['uid', '上传人'],
                ['disk', '上传驱动'],
                ['original_name', '名称'],
                ['size', '大小'],
                ['mime_type', '类型'],
                ['ext', '后缀'],
                ['upload_time', '上传时间', 'datetime'],
                ['right_button', '操作', 'btn'],
            ])
            ->addTopButtons('enable,disable,delete') // 批量添加顶部按钮
            ->addRightButtons('delete') // 批量添加右侧按钮

        ;
    }
    /**
     * 遍历获取目录下的指定类型的附件
     * @param string $path 路径
     * @param string $allowFiles 允许查看的类型
     * @param array $files 文件列表
     * @return array|null
     * @author dragonlhp <1458485514@qq.com>
     */
    #[RequestMethod(['GET,POST'])]
    #[RequestTitle('列表')]
    public function getfiles($path = '', $allowFiles = '', &$files = array())
    {
        if (!is_dir($path)) {
            return null;
        }

        if (substr($path, strlen($path) - 1) != '/') {
            $path .= '/';
        }

        $handle = opendir($path);
        while (false !== ($file = readdir($handle))) {
            if ($file != '.' && $file != '..') {
                $path2 = $path . $file;
                if (is_dir($path2)) {
                    $this->getfiles($path2, $allowFiles, $files);
                } else {
                    if (preg_match("/\.(" . $allowFiles . ")$/i", $file)) {
                        $files[] = array(
                            'url' => str_replace("\\", "/", substr($path2, strlen($_SERVER['DOCUMENT_ROOT']))),
                            'mtime' => filemtime($path2),
                        );
                    }
                }
            }
        }
        return $files;
    }

    /**
     * 启用附件
     * @param array $record 行为日志
     * @return mixed
     * @author dragonlhp <1458485514@qq.com>
     */
    #[RequestMethod(['POST'])]
    #[RequestTitle('启用')]
    public function enable()
    {
        return $this->setStatus('enable');
    }

    /**
     * 禁用附件
     * @param array $record 行为日志
     * @return mixed
     * @author dragonlhp <1458485514@qq.com>
     */
    #[RequestMethod(['GET,POST'])]
    #[RequestTitle('禁用')]
    public function disable()
    {
        return $this->setStatus('disable');
    }

    /**
     * 设置附件状态：删除、禁用、启用
     * @param string $type 类型：delete/enable/disable
     * @param array $record
     * @throws \think\Exception
     * @throws \think\db\Express
     * @author dragonlhp <1458485514@qq.com>
     */
    #[RequestMethod(['GET,POST'])]
    #[RequestTitle('状态')]
    public function setStatus($type = '', $record = [])
    {
        $ids = $this->request->isPost() ? input('post.ids/a') : input('param.ids');
        $ids = is_array($ids) ? implode(',', $ids) : $ids;
        return parent::setStatus($type, ['attachment_' . $type, 'admin_attachment', 0, session('uid'), $ids]);
    }

    /**
     * 删除附件
     * @param string $ids 附件id
     * @throws \think\Exception
     * @throws \think\db\Express
     * @author dragonlhp <1458485514@qq.com>
     */
    #[RequestMethod(['DELETE'])]
    #[RequestTitle('删除')]
    public function delete($ids = '')
    {
        $ids = $this->request->isDelete() ? input('post.ids/a') : input('param.ids');
        if (empty($ids)) {
            return $this->error('缺少主键');
        }

        $files_path = AttachmentModel::where('id', 'in', $ids)->column('path,thumb', 'id');

        foreach ($files_path as $value) {
            $real_path = realpath(config('app.upload_path') . '/../' . $value['path']);
            $real_path_thumb = realpath(config('app.upload_path') . '/../' . $value['thumb']);

            if (is_file($real_path) && !unlink($real_path)) {
                return $this->error('删除失败');
            }
            if (is_file($real_path_thumb) && !unlink($real_path_thumb)) {
                return $this->error('删除缩略图失败');
            }
        }
        if (AttachmentModel::where('id', 'in', $ids)->delete()) {
            // 记录行为
            $ids = is_array($ids) ? implode(',', $ids) : $ids;
            action_log('attachment_delete', 'admin_attachment', 0, session('uid'), $ids);
            return $this->success('删除成功');
        } else {
            return $this->error('删除失败');
        }
    }

    /**
     * 快速编辑
     * @param array $record 行为日志
     * @return mixed
     * @author dragonlhp <1458485514@qq.com>
     */
    #[RequestMethod(['GET,POST'])]
    #[RequestTitle('快速编辑')]
    public function quickEdit()
    {
        $id = input('post.pk', '');
        return parent::quickEdit(['attachment_edit', 'admin_attachment', 0, session('uid'), $id]);
    }
}